const request = {}
const headers = {}

/* 解决多个请求闪烁问题 */
let needLoadingRequestCount = 0

function showFullScreenLoading() {
	if (needLoadingRequestCount === 0) {
		uni.showLoading({
			title: '加载中',
			mask: true,
		})
	}
	needLoadingRequestCount++
}

function tryHideFullScreenLoading() {
	if (needLoadingRequestCount <= 0) return
	needLoadingRequestCount--
	if (needLoadingRequestCount === 0) {
		uni.hideLoading({ noConflict: true, })
	}
}
/* 解决多个请求闪烁问题--END */


request.globalRequest = (url, method, data, power, isShowLoading = true) => {
	const user = uni.getStorageSync('user')
	switch (power) {
		case 1:
			headers['platform'] = 'mini'
			headers['token'] = uni.getStorageSync('token')
		default:
			headers['platform'] = 'mini'
	}
	if (isShowLoading) {
		showFullScreenLoading()
	}
	return uni.request({
		timeout: 10000,
		url: process.env.VUE_APP_BASE_URL + url,
		method,
		data: data,
		dataType: 'json',
		header: headers
	}).then(response => {
		let res = response[1]
		tryHideFullScreenLoading()
		if (res.data.code == 200 || res.data.code == -1) {
			return res.data
		} else {
			throw res.data
		}

	}).catch(parmas => {

		tryHideFullScreenLoading()
		switch (parmas.code) {
			case 104:
				uni.showToast({
					title: '登录已过期，请重新登录',
					icon: 'none',
				})
				setTimeout(() => {
					uni.clearStorageSync()
					uni.redirectTo({ url: '/pages/login/login' })
				}, 1000)
				break
			case 104000:
				wx.request({
					url: process.env.VUE_APP_BASE_URL + '/st-permission-server/saas/inner/wx/program/unbind',
					method: 'POST',
					data: {
						phoneNum: user ? JSON.parse(user).loginCode : '',
						key: uni.getStorageSync('programLoginData') ? JSON.parse(uni.getStorageSync('programLoginData'))
							.key : '',
						platformType: 1016,
					},
					header: {
						token: uni.getStorageSync('token'),
						loginCode: user ? JSON.parse(user).loginCode : '',
						platform: 'OMO_MINI_EDU'
					},
					success: data => {
						if (data.data.code == 0) {
							wx.showToast({
								title: '账号已被其他设备登录，请重新输入',
								icon: 'none',
							})
						}

					},
					fail: res => {
						return
					}
				})

				break
			default:
				uni.showToast({
					title: parmas.msg || '操作失败',
					icon: 'none'
				})
				return Promise.reject()
		}
	})
}
export default request